from django.shortcuts import render,HttpResponse

# Create your views here.

def index(request):
    return HttpResponse("Hello, Along")

from django.db.models import Q # 相当于or
from users.models import UserProfile

def check(username=None, password=None):
    try:
        user = UserProfile.objects.get(Q(username__exact=username) | Q(email__exact=username))
        # 用户可以用email和username进行登录，引用Q 相当于or
        if user.check_password(password):
            return user
        else:
            return False
    except Exception as error:
        print(error)
        return None


from django.http import JsonResponse

def user_login(request):
    username = request.POST.get('username', '')  # 前端返回的username
    password = request.POST.get('password', '') # 前端返回的password
    user = check(username=username, password=password) # 对username和password进行验证
    if user is not None:
        if user is not False:
            data = {'msg': '登录成功','username': username}
            return JsonResponse({'result': data})
        else:
            data = {'msg': '密码错误'}
            return JsonResponse({'result': data})
    else:
        data = {'msg': '用户不存在'}
        return JsonResponse({'result': data})